const webpack = require('webpack')
const buildDate = JSON.stringify(new Date().toLocaleString())
const createThemeColorReplacerPlugin = require('./config/plugin.config')
const isProd = process.env.NODE_ENV === 'production'

const cdn = {
  // webpack build externals
  externals: {
    vue: 'Vue',
    'vue-router': 'VueRouter',
    vuex: 'Vuex',
    axios: 'axios'
  },
  css: [],
  // https://unpkg.com/browse/vue@2.6.10/
  js: [
    'https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js',
    'https://cdn.jsdelivr.net/npm/vue-router@3.5.2/dist/vue-router.min.js',
    'https://cdn.jsdelivr.net/npm/vuex@3.1.1/dist/vuex.min.js',
    'https://cdn.jsdelivr.net/npm/axios@0.21.1/dist/axios.min.js'
  ]
}

// vue.config.js
const vueConfig = {
  // 后台
  devServer: {
    hot: true, //修改浏览器会重新刷新
    proxy: {
      '/api': {
        target: 'http://localhost:3000',
        ws: false, // 需要websocket 开启
        changeOrigin: true, //true允许跨域
      }
    }
  },
  productionSourceMap: false, // 不打包.map文件
  lintOnSave: false, //禁用lint检查代码
  // 自定义链子
  chainWebpack: config => {
    // config.resolve.alias.set('@$', resolve('src'))

    // const svgRule = config.module.rule('svg')
    // svgRule.uses.clear()
    // svgRule
    //   .oneOf('inline')
    //   .resourceQuery(/inline/)
    //   .use('vue-svg-icon-loader')
    //   .loader('vue-svg-icon-loader')
    //   .end()
    //   .end()
    //   .oneOf('external')
    //   .use('file-loader')
    //   .loader('file-loader')
    //   .options({
    //     name: 'assets/[name].[hash:8].[ext]'
    //   })

    // 生产环境打包cdn
    if (isProd) {
      config.plugin('html').tap(args => {
        args[0].cdn = cdn
        return args
      })
    }
  },

  configureWebpack: {
    // webpack plugins
    plugins: [
      // Ignore all locale files of moment.js
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
      new webpack.DefinePlugin({
        APP_VERSION: `"${require('./package.json').version}"`,
        GIT_HASH: 'JSON.stringify(getGitHash())',
        BUILD_DATE: buildDate
      })
    ],
    // if prod, add externals
    externals: isProd ? cdn.externals : {}
  },
  // 加载less less-loader@6.0.0以上版本
  css: {
    loaderOptions: {
      less: {
        // lessOptions: {
          // If you are using less-loader@5 please spread the lessOptions to options directly
          modifyVars: {
            // 'primary-color': '#1DA57A',
            'btn-font-size-sm': '12px',
            'border-radius-base': '2px',
          },
          javascriptEnabled: true,
        // },
      },
    },
  }
}

// preview.pro.loacg.com only do not use in your production;
if (process.env.VUE_APP_PREVIEW === 'true') {
  console.log('VUE_APP_PREVIEW', true)
  // add `ThemeColorReplacer` plugin to webpack plugins
  vueConfig.configureWebpack.plugins.push(createThemeColorReplacerPlugin())
}

module.exports = vueConfig
